<template>
  <div class="announcement-list">
    <div class="page-header">
      <h1>公告管理</h1>
      <el-button type="primary" @click="createAnnouncement">
        <el-icon><Plus /></el-icon>
        新建公告
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索标题或内容"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部状态" clearable>
            <el-option
              v-for="option in ANNOUNCEMENT_STATUS_OPTIONS"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="类型">
          <el-select v-model="searchForm.type" placeholder="全部类型" clearable>
            <el-option
              v-for="option in ANNOUNCEMENT_TYPE_OPTIONS"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="目标用户">
          <el-select v-model="searchForm.targetType" placeholder="全部用户" clearable>
            <el-option
              v-for="option in ANNOUNCEMENT_TARGET_TYPE_OPTIONS"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="searchAnnouncements">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 公告列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="announcements"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="title" label="标题" min-width="200">
          <template #default="{ row }">
            <div class="title-cell">
              <el-link type="primary" @click="viewAnnouncement(row)">
                {{ row.title }}
              </el-link>
              <el-tag v-if="row.isPinned" type="warning" size="small" style="margin-left: 8px">
                置顶
              </el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="type" label="类型" width="120">
          <template #default="{ row }">
            <el-tag :color="getAnnouncementTypeInfo(row.type).color" size="small">
              {{ getAnnouncementTypeInfo(row.type).label }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="targetType" label="目标用户" width="120">
          <template #default="{ row }">
            {{ getAnnouncementTargetTypeLabel(row.targetType) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :color="getAnnouncementPriorityInfo(row.priority).color" size="small">
              {{ getAnnouncementPriorityInfo(row.priority).label }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getAnnouncementStatusInfo(row.status).type" size="small">
              {{ getAnnouncementStatusInfo(row.status).label }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="readCount" label="阅读量" width="100" />
        
        <el-table-column prop="publisherName" label="发布者" width="120" />
        
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="viewAnnouncement(row)">
              查看
            </el-button>
            <el-button type="text" size="small" @click="editAnnouncement(row)">
              编辑
            </el-button>
            <el-button 
              v-if="row.status === 'DRAFT' || row.status === 'SCHEDULED'"
              type="text" 
              size="small" 
              @click="publishAnnouncement(row)"
            >
              发布
            </el-button>
            <el-button 
              v-if="row.status === 'PUBLISHED'"
              type="text" 
              size="small" 
              @click="cancelAnnouncement(row)"
            >
              取消
            </el-button>
            <el-button 
              type="text" 
              size="small" 
              style="color: #f56c6c"
              @click="deleteAnnouncement(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { 
  announcementApi,
  ANNOUNCEMENT_TYPE_OPTIONS,
  ANNOUNCEMENT_TARGET_TYPE_OPTIONS,
  ANNOUNCEMENT_STATUS_OPTIONS,
  getAnnouncementTypeInfo,
  getAnnouncementTargetTypeLabel,
  getAnnouncementPriorityInfo,
  getAnnouncementStatusInfo,
  formatDateTime
} from '@/api/announcement'

const router = useRouter()

const loading = ref(false)
const announcements = ref([])

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: '',
  type: '',
  targetType: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 加载公告列表
const loadAnnouncements = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page - 1,
      size: pagination.size,
      ...searchForm
    }
    
    // 移除空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const response = await announcementApi.getAnnouncements(params)
    announcements.value = response.data?.content || []
    pagination.total = response.data?.totalElements || 0
  } catch (error) {
    console.error('加载公告列表失败:', error)
    ElMessage.error('加载公告列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索公告
const searchAnnouncements = () => {
  pagination.page = 1
  loadAnnouncements()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    keyword: '',
    status: '',
    type: '',
    targetType: ''
  })
  pagination.page = 1
  loadAnnouncements()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadAnnouncements()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadAnnouncements()
}

// 新建公告
const createAnnouncement = () => {
  router.push('/announcements/create')
}

// 查看公告
const viewAnnouncement = (announcement) => {
  router.push(`/announcements/${announcement.id}`)
}

// 编辑公告
const editAnnouncement = (announcement) => {
  router.push(`/announcements/edit/${announcement.id}`)
}

// 发布公告
const publishAnnouncement = async (announcement) => {
  try {
    await ElMessageBox.confirm(
      `确定要发布公告"${announcement.title}"吗？`,
      '确认发布',
      { type: 'warning' }
    )
    
    await announcementApi.publishAnnouncement(announcement.id)
    ElMessage.success('公告发布成功')
    loadAnnouncements()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('发布公告失败:', error)
      ElMessage.error('发布公告失败')
    }
  }
}

// 取消发布公告
const cancelAnnouncement = async (announcement) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消发布公告"${announcement.title}"吗？`,
      '确认取消',
      { type: 'warning' }
    )
    
    await announcementApi.cancelAnnouncement(announcement.id)
    ElMessage.success('取消发布成功')
    loadAnnouncements()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消发布失败:', error)
      ElMessage.error('取消发布失败')
    }
  }
}

// 删除公告
const deleteAnnouncement = async (announcement) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除公告"${announcement.title}"吗？此操作不可恢复。`,
      '确认删除',
      { type: 'error' }
    )
    
    await announcementApi.deleteAnnouncement(announcement.id)
    ElMessage.success('删除成功')
    loadAnnouncements()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除公告失败:', error)
      ElMessage.error('删除公告失败')
    }
  }
}

onMounted(() => {
  loadAnnouncements()
})
</script>

<style scoped>
.announcement-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.title-cell {
  display: flex;
  align-items: center;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
